package com.nopay.dxdwphone.baiduocr;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class OCRTokenAPI {

    private static String mToken;

    private static final String HOST = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String API_KEY = "zuFseTcV73LSM4MBHXv8RBTZ";
    private static final String SECRET_KEY = "msdgIsMNwsQnEX05gkLVdB3vcgC2oqNd";

    public static String getToken() {
        if(mToken != null) return mToken;
        return getAuth();
    }

    private static String getAuth() {
        String tokenUrl = HOST + "?grant_type=client_credentials"
                + "&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY;

        try {
            URL realUrl = new URL(tokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }
}
